package com.tzx.multinetrequest

import android.annotation.SuppressLint
import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.navigation.fragment.findNavController
import com.example.myapplication.network.NetworkRequestHelper
import com.tzx.multinetrequest.databinding.FragmentSecondBinding
import java.io.IOException

/**
 * 切换当前进程的网络类型（WIFI、蜂窝网络）
 * 测试设备1：
 * 厂商: Xiaomi
 * 型号: 2201122C
 * 系统版本: 15
 * API级别: 35
 *
 *  测试设备2：
 * 厂商: Xiaomi
 * 型号: 24129PN74C
 * 系统版本: 15
 * API级别: 35
 *
 * 测试结果：
 * 1、不选择默认更随手机系统，会随手机系统变化；
 * 2、如果wifi可以，选择wifi，请求成功；
 * 3、如果移动数据可以，选择移动数据，请求成功；
 * 4、如果移动数据不能用，选择移动数据，选择无效；
 * 5、如果wifi不能用，选择wifi，选择无效；
 * 6、无论选择wifi和移动数据成功后，选择的网络断掉且重新恢复后，需要进行重新选择，否则依旧无法进行网络请求；
 * 6、无论选择wifi和移动数据成功后，选择的网络断掉无法自动切换到其他可用网络，需要进行重新选择，否则依旧无法进行网络请求；
 * 选择的网络断掉之后：接口请求抛异常：Unable to resolve host "www.baidu.com":No address associated with hostname
 */
class SwitchNetworkFragment : Fragment() {

    private var _binding: FragmentSecondBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    /**
     * null：绑定
     * true：绑定wifi
     * false：绑定移动数据
     */
    private var processBindNetworkWithWIFI: Boolean? = null
    private var requestSuccess: Int = 0

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {

        _binding = FragmentSecondBinding.inflate(inflater, container, false)
        return binding.root

    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        binding.lookNetworkType.setOnClickListener {
            val cm: ConnectivityManager = requireContext().getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
            val content = StringBuilder()
            val network = cm.boundNetworkForProcess
            if (network != null) {
                val caps = cm.getNetworkCapabilities(network)
                if (caps != null) {
                    if (caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
                        content.append("当前进程绑定网络类型：Wi-Fi")
                        updateBindNetworkType(true)
                    } else if (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)) {
                        content.append("当前进程绑定网络类型：移动数据")
                        updateBindNetworkType(false)
                    } else {
                        content.append("当前进程绑定了其他网络类")
                    }
                } else {
                    content.append("绑定的网络无能力信息")
                    updateBindNetworkType(null)
                }
            } else {
                content.append("当前进程未绑定特定网络（使用系统默认路由）")
            }
            binding.networkType.text = content.toString()
        }
        updateBindNetworkType(null)
        binding.setNetworkWifi.setOnClickListener {
            NetworkRequestHelper(this.requireContext()).switchToWifiData()
        }
        binding.setNetworkCellular.setOnClickListener {
            NetworkRequestHelper(this.requireContext()).switchToMobileData()
        }
        binding.request.setOnClickListener {
            requestNetwork()
        }
    }

    @SuppressLint("SetTextI18n")
    private fun updateBindNetworkType(isWifi: Boolean?) {
        processBindNetworkWithWIFI = isWifi
        if (processBindNetworkWithWIFI == null) {
            binding.selectNetworkType.text = "当前选择的网络类型: 未绑定"
        } else if (processBindNetworkWithWIFI == true) {
            binding.selectNetworkType.text = "当前选择的网络类型: Wifi"
        } else {
            binding.selectNetworkType.text = "当前选择的网络类型: 流量"
        }
    }

    @SuppressLint("SetTextI18n")
    private fun requestNetwork() {
        binding.requestContent.text = "正在请求中..."
        val helper = NetworkRequestHelper(this.requireContext())
        Thread(Runnable {
            try {
                val response =
                    helper.makeRequestOnNetwork(null, "https://www.baidu.com")
                binding.requestContent.post {
                    requestSuccess++
                    binding.requestContent.text = "第${requestSuccess}次请求成功\n$response"
                }
            } catch (e: IOException) {
                binding.requestContent.post {
                    requestSuccess++
                    binding.requestContent.text = "exception: ${e.message}"
                }
            }
        }).start()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}